package com.zhoug.common3.imageloader;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import com.bumptech.glide.request.target.ImageViewTarget;

import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

/**
 * 占位图和错误图设置成圆形图片
 * @Author 35574
 * @Date 2021/9/7
 * @Description
 */
public class CircleImageTarget<Z> extends ImageViewTarget<Z> {
    private static final String TAG = ">>>CircleImageTarget";

    public CircleImageTarget(ImageView view) {
        super(view);
    }

    @Override
    protected void setResource(@Nullable Z resource) {
        if(resource instanceof Bitmap){
            view.setImageBitmap((Bitmap) resource);
        }else if(resource instanceof Drawable){
            view.setImageDrawable((Drawable) resource);
        }
    }


    @Override
    public void setDrawable(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            bindCircleBitmapToImageView(((BitmapDrawable) drawable).getBitmap());
        } else {
            super.setDrawable(drawable);
        }
    }

    /**
     * 通过RoundedBitmapDrawable绘制圆形Bitmap,且加载ImageView.
     * @param bitmap
     */
    private void bindCircleBitmapToImageView(Bitmap bitmap){
        RoundedBitmapDrawable bitmapDrawable=  RoundedBitmapDrawableFactory.create(view.getContext().getResources(),bitmap);
        bitmapDrawable.setCircular(true);
        view.setImageDrawable(bitmapDrawable);
    }


}
